#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "keyboard.h"

#define BUF_LENGTH 7

int main(int argc, char *argv[])
{ 
    int sfd;
    if(-1==(sfd=socket(AF_INET, SOCK_STREAM, 0)))         //创建套接字
    {
        perror("socket failed\n");
       exit(-1);
    }
    struct sockaddr_in add;                              //定义结构体变量
    add.sin_family=AF_INET;
    add.sin_port=htons(2222);
    add.sin_addr.s_addr=inet_addr("0.0.0.0");
    if(-1==bind(sfd,(struct sockaddr*)&add,sizeof(add)))         //绑定
    {
        perror("bind failed\n");
        fflush(stdout);
        exit(-1);
    }
    if(-1==listen(sfd, 5))   //监听套接字 backlog 客户端连接请求队列的长度，表示同一时刻接受客户端的请求数
    {                       //使套接字变成监听套接字
        perror("listen failed\n");
        fflush(stdout);
         exit(-1);

    }
    //接受连接
    while(1)
    {
        struct sockaddr_in caddr;
        socklen_t len=sizeof(caddr);
        int afd=accept(sfd, (struct sockaddr*)&caddr,&len);      //阻塞等待，接受客户端连接，建立通信管道
            //如果请求队列中没有客户端请求就阻塞直到有请求就连接
        if(afd==-1)
        {                                                //成功返回消息管道的ID号
            //如果不需要保存客户端的ip地址和端口号，则第2，3传为NULL
            perror("accept failed\n");
            fflush(stdout);
            exit(-1);
        }
        printf("afd=%d\n",afd);
        printf("port=%u\naddr=%s\n",ntohs(caddr.sin_port),inet_ntoa(caddr.sin_addr));
        fflush(stdout);
        char buf[BUF_LENGTH]={0};
        //数据交互
        while(1)
        {
             	int err = 1;
		recv(afd,buf,BUF_LENGTH,MSG_DONTWAIT);
           	if( (buf[0] == 'T' )&& (buf[1] == 'C') &&( buf[2] == 'P' ) )
		{
			err = write(afd, buf, BUF_LENGTH);
			printf("%s",buf);
			fflush(stdout);
			memset(buf,0,BUF_LENGTH);
           	}
		
		if('w'  == nonblocking_input() )
		{
			err = send(afd ,"w_gogo\n ",7,0);
		}
		if('a'  == nonblocking_input() )
                {
                        err = send(afd ,"a_gogo\n ",7,0);
                }
		if('s'  == nonblocking_input() )
                {
                        err = send(afd ,"s_gogo\n ",7,0);
                }
		if('d'  == nonblocking_input() )
                {
                        err = send(afd ,"d_gogo\n ",7,0);
                }

		if('q' == nonblocking_input())
		{
			err = send(afd ,"exit\n ",7,0);
			close(afd);
			break;
		}
		if(err <  0)
		{
			printf("Server shutdown");

			close(afd);
			break;
		}
        }
        //当read,recv函数连接断开时，返回0
        //关闭套接字
    }
    close(sfd);
    return 0;
 
} 
